﻿$(document).ready(function () {
    $("#loading").hide();
    $("#wallPostTool").hide();
    $("#attachmentForm").hide();
    $("#lastMessage").hide();
    var attFIle = false;
    var stopLoad = false;

    $("#attFile").click(function () {
        attFIle = true;
        $("#attachmentForm").show("bind");
    });

    $("#noAttFile").click(function () {
        attFIle = false;
        $("#attachmentForm").hide("bind");
    });

    $("#wallPostInput").click(function () {
        $(this).attr("rows", 5);
        if ($("#wallPostTool").is(":hidden"))
            $("#wallPostTool").show("clip");
    });
    $("#wallPostSend").click(function () {
        if ($("#wallPostInput").val().length < 1 || typeof YourId == 'undefined')
            return false;

        if (attFIle) {
            if ($("#wallPublic").is(":checked"))
                $("#attPublic").val('1');
            $("#attachmentForm").ajaxSubmit({
                beforeSubmit: function () {
                    $("#wallPost :input").prop('disabled', true);
                    $("#loading").show();
                },
                success: function (responseText, statusText, xhr, $form) {
                    var res = $.parseJSON(responseText);
                    if (typeof res.error != 'undefined') {
                        alert(res.error);
                        return false;
                    }
                    $('#attContent').val('');
                    attFIle = false;
                    SendPost(res);
                }
            });
        } else {
            SendPost();
        }
    });
    function SendPost(res) {
        $("#wallPost :input").prop('disabled', true);
        $("#loading").show();
        var wall = new Object();
        wall.GId = $("#GId").val();
        wall.GWContent = $('<div/>').text($("#wallPostInput").val()).html();
        wall.GWTime = "2014-01-06T15:45:00";
        wall.WriterId = YourId;
        if (typeof res != 'undefined') {
            wall.AId = res.AId;
        }
        if ($("#wallPublic").is(":checked"))
            wall.isPublic = true;
        else
            wall.isPublic = false;
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            url: "/CoreService.svc/GroupWalls",
            data: JSON.stringify(wall),
            success: function (data, textStatus, jqXHR) {
                //append
                $("#wallMessContainer").prepend('<tr><td class="wallLeftCol"><img width="40px" height="60px" src="' + YourAvatar + '" /></td>' +
                '<td class="wallRightCol"><div class="wallContent"><a href="/' + YourUserName + '/Home"><b>' + YourDisplayName + '</b></a>:' + wall.GWContent + '</div>' +
                ((typeof res != 'undefined') ? ((res.isImage) ? '<div class="wallContent"><img width="450" src="' + res.ASource + '" alt="attachment" /></div>' : '<div class="wallContent"><a href="/Home/DownloadAttachment/' + res.AId + '">' + res.AName + '</a></div>') : '') +
                '<div><textarea data-id="' + data.d.GWId + '" class="wallCommentInput" cols="40" rows="1" style="width: 400px;"></textarea></div></td></tr>');
                $("#wallPostInput").val('');
                $("#wallPost :input").prop('disabled', false);
                $("#attachmentForm").hide("clip");
                $("#wallPostTool").hide("clip");
                $("#loading").hide();
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert(errorThrown + "\nYour data not submit yet. Check the conection and submit agian.");
            }
        });
    }

    $(".wallCommentInput").live("focusin", function () {
        $(this).attr("rows", 2);
        $(this).css('background-color', 'white');
    });

    $(".wallCommentInput").live("focusout", function () {
        $(this).attr("rows", 1);
        $(this).css('background-color', '#DBD7DE');
    });

    $(".wallCommentInput").live("keypress", function (e) {
        var currentInput = $(this);
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13) { //Enter keycode
            if (currentInput.val().length < 1 || typeof YourId == 'undefined')
                return false;

            var wall = new Object();
            wall.GId = $("#GId").val();
            wall.GWContent = currentInput.val();
            wall.GWTime = "2014-01-06T15:45:00";
            wall.WriterId = YourId;
            wall.ParentGWId = currentInput.attr("data-id");

            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                url: "/CoreService.svc/GroupWalls",
                data: JSON.stringify(wall),
                success: function (data, textStatus, jqXHR) {
                    $('<div class="wallComment ui-corner-right"><img width="30px" height="45px" src="' + YourAvatar + '" />' +
                    '<span class="wallCommentContent"><b><a href="/' + YourUserName + '/Home">' + YourDisplayName + '</a></b>:' + wall.GWContent + '</span></div>').insertBefore(currentInput);
                    currentInput.val('');
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    alert(errorThrown + "\nYour data not submit yet. Check the conection and submit agian.");
                }
            });
            return false;
        }
    });
    function LoadWall(skip) {
        var query = "/CoreService.svc/GetGroupWall?gid=" + GroupId + "&$filter=ParentGWId%20eq%20null&$orderby=GWId%20desc&$expand=Writer,Attachments,Children/Writer&$select=GWId,GWContent,GWTime,Writer/UserName,Writer/DisplayName,Writer/Avatar,Attachments/ASource,Attachments/isImage,Children/GWContent,Children/GWId,Children/GWTime,Children/Writer/UserName,Children/Writer/DisplayName,Children/Writer/Avatar&$skip=" + skip + "&$top=20";
        $.getJSON(query, function (result) {
            if (result.d.length < 20)
                stopLoad = true;
            $.each(result.d, function (i, WMess) {
                var commentList = '';
                $.each(WMess.Children, function (j, WComment) {
                    commentList += ('<div class="wallComment ui-corner-right"><img width="30px" height="45px" src="' + WComment.Writer.Avatar + '" />' +
                    '<span class="wallCommentContent"><b><a href="/' + WComment.Writer.UserName + '/Home">' + WComment.Writer.DisplayName + '</a></b>:' + WComment.GWContent + '</span></div>');
                });
                $("#wallMessContainer").append('<tr><td class="wallLeftCol"><img width="40px" height="60px" src="' + WMess.Writer.Avatar + '" /></td>' +
                '<td class="wallRightCol"><div class="wallContent"><a href="/' + WMess.Writer.UserName + '/Home"><b>' + WMess.Writer.DisplayName + '</b></a>:' + WMess.GWContent + '</div>' +
                ((WMess.Attachments != null) ? ((WMess.Attachments.isImage) ? '<div class="wallContent"><img width="450" src="' + WMess.Attachments.ASource + '" alt="attachment" /></div>' : '<div class="wallContent"><a href="' + WMess.Attachments.ASource + '">' + WMess.Attachments.AName + '</a></div>') : '') +
                commentList +
                '<div><textarea data-id="' + WMess.GWId + '" class="wallCommentInput" cols="40" rows="1" style="width: 400px;"></textarea></div></td></tr>');
            });
        });
    }
    var currentRow = 20
    $(window).scroll(function () {
        if (($(window).scrollTop() == $(document).height() - $(window).height()) && !stopLoad) {
            $("#lastMessage").show();
            LoadWall(currentRow);
            currentRow = currentRow + 20;
            $("#lastMessage").hide();
        }
    });
    $("#okSubmit").click(function () {
        if (typeof YourId != "undefined") {
            var frequest = new Object();
            frequest.GId = $("#GId").val();
            frequest.GRHi = $("#sayHi").val();
            frequest.UserId = YourId;
            frequest.GRTime = "2014-01-06T15:45:00";
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                url: "/CoreService.svc/GroupRequests",
                data: JSON.stringify(frequest),
                success: function (data, textStatus, jqXHR) {
                    alert("ok");
                    $("#submitedDialog").dialog("destroy");
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    alert(errorThrown + "\nnook");
                }
            });
        }
    });
});